import { useNavigate, useLocation } from 'react-router-dom';
import type { NavigateOptions } from 'react-router-dom';

type nextType = (path: string, options?: NavigateOptions) => void;
type callBackType = (
    to: string,
    from: string,
    next: (...args: Partial<Parameters<nextType>>) => void
) => void;

const useNavigateGuard = () => {
    const navigate = useNavigate();
    const { pathname } = useLocation();

    const next: nextType = (path, options) => {
        navigate(path, options);
    };

    return {
        navigate: (to: string, options?: NavigateOptions, cb?: callBackType) => {
            if (!cb) {
                next(to, options);
                return;
            }

            cb(to, pathname, (path, options) => next(path ?? to, options));
        },
    };
};

export default useNavigateGuard;
